import { useState } from 'react'
import './StateManagement.css'

// 基本计数器组件
function Counter() {
  const [count, setCount] = useState(0)

  return (
    <div className="counter">
      <h3>计数器: {count}</h3>
      <button onClick={() => setCount(count + 1)}>增加</button>
      <button onClick={() => setCount(count - 1)}>减少</button>
      <button onClick={() => setCount(0)}>重置</button>
    </div>
  )
}

// 文本输入组件
function TextInput() {
  const [text, setText] = useState('')

  return (
    <div className="text-input">
      <h3>文本输入</h3>
      <input 
        type="text"
        value={text}
        onChange={(e) => setText(e.target.value)}
        placeholder="输入一些文字..."
      />
      <p>你输入了: {text}</p>
      <p>字符数: {text.length}</p>
    </div>
  )
}

// 复选框组件
function CheckboxExample() {
  const [isChecked, setIsChecked] = useState(false)
  const [hobbies, setHobbies] = useState([])

  const handleHobbyChange = (hobby) => {
    setHobbies(prev => 
      prev.includes(hobby) 
        ? prev.filter(h => h !== hobby)
        : [...prev, hobby]
    )
  }

  return (
    <div className="checkbox-example">
      <h3>复选框示例</h3>
      
      <div className="checkbox-item">
        <label>
          <input 
            type="checkbox"
            checked={isChecked}
            onChange={(e) => setIsChecked(e.target.checked)}
          />
          我同意条款和条件
        </label>
        <p>状态: {isChecked ? '已同意' : '未同意'}</p>
      </div>

      <div className="checkbox-item">
        <h4>选择你的爱好:</h4>
        {['阅读', '运动', '音乐', '旅行', '编程'].map(hobby => (
          <label key={hobby}>
            <input 
              type="checkbox"
              checked={hobbies.includes(hobby)}
              onChange={() => handleHobbyChange(hobby)}
            />
            {hobby}
          </label>
        ))}
        <p>已选择的爱好: {hobbies.join(', ') || '无'}</p>
      </div>
    </div>
  )
}

// 单选按钮组件
function RadioExample() {
  const [gender, setGender] = useState('')
  const [theme, setTheme] = useState('light')

  return (
    <div className="radio-example">
      <h3>单选按钮示例</h3>
      
      <div className="radio-group">
        <h4>性别:</h4>
        <label>
          <input 
            type="radio"
            name="gender"
            value="male"
            checked={gender === 'male'}
            onChange={(e) => setGender(e.target.value)}
          />
          男
        </label>
        <label>
          <input 
            type="radio"
            name="gender"
            value="female"
            checked={gender === 'female'}
            onChange={(e) => setGender(e.target.value)}
          />
          女
        </label>
        <label>
          <input 
            type="radio"
            name="gender"
            value="other"
            checked={gender === 'other'}
            onChange={(e) => setGender(e.target.value)}
          />
          其他
        </label>
        <p>选择的性别: {gender || '未选择'}</p>
      </div>

      <div className="radio-group">
        <h4>主题:</h4>
        <label>
          <input 
            type="radio"
            name="theme"
            value="light"
            checked={theme === 'light'}
            onChange={(e) => setTheme(e.target.value)}
          />
          浅色
        </label>
        <label>
          <input 
            type="radio"
            name="theme"
            value="dark"
            checked={theme === 'dark'}
            onChange={(e) => setTheme(e.target.value)}
          />
          深色
        </label>
        <p>当前主题: {theme === 'light' ? '浅色' : '深色'}</p>
      </div>
    </div>
  )
}

// 下拉选择组件
function SelectExample() {
  const [city, setCity] = useState('')
  const [multiSelect, setMultiSelect] = useState([])

  const cities = ['北京', '上海', '广州', '深圳', '杭州', '成都']
  const skills = ['JavaScript', 'React', 'Vue', 'Angular', 'Node.js', 'Python']

  const handleMultiSelectChange = (e) => {
    const selectedOptions = Array.from(e.target.selectedOptions, option => option.value)
    setMultiSelect(selectedOptions)
  }

  return (
    <div className="select-example">
      <h3>下拉选择示例</h3>
      
      <div className="select-group">
        <h4>选择城市:</h4>
        <select value={city} onChange={(e) => setCity(e.target.value)}>
          <option value="">请选择城市</option>
          {cities.map(city => (
            <option key={city} value={city}>{city}</option>
          ))}
        </select>
        <p>选择的城市: {city || '未选择'}</p>
      </div>

      <div className="select-group">
        <h4>选择技能 (多选):</h4>
        <select multiple value={multiSelect} onChange={handleMultiSelectChange}>
          {skills.map(skill => (
            <option key={skill} value={skill}>{skill}</option>
          ))}
        </select>
        <p>选择的技能: {multiSelect.join(', ') || '未选择'}</p>
      </div>
    </div>
  )
}

// 对象状态管理
function ObjectState() {
  const [user, setUser] = useState({
    name: '',
    email: '',
    age: '',
    address: {
      city: '',
      street: ''
    }
  })

  const updateField = (field, value) => {
    setUser(prev => ({
      ...prev,
      [field]: value
    }))
  }

  const updateAddress = (field, value) => {
    setUser(prev => ({
      ...prev,
      address: {
        ...prev.address,
        [field]: value
      }
    }))
  }

  return (
    <div className="object-state">
      <h3>对象状态管理</h3>
      
      <div className="form-group">
        <label>姓名:</label>
        <input 
          type="text"
          value={user.name}
          onChange={(e) => updateField('name', e.target.value)}
        />
      </div>

      <div className="form-group">
        <label>邮箱:</label>
        <input 
          type="email"
          value={user.email}
          onChange={(e) => updateField('email', e.target.value)}
        />
      </div>

      <div className="form-group">
        <label>年龄:</label>
        <input 
          type="number"
          value={user.age}
          onChange={(e) => updateField('age', e.target.value)}
        />
      </div>

      <div className="form-group">
        <label>城市:</label>
        <input 
          type="text"
          value={user.address.city}
          onChange={(e) => updateAddress('city', e.target.value)}
        />
      </div>

      <div className="form-group">
        <label>街道:</label>
        <input 
          type="text"
          value={user.address.street}
          onChange={(e) => updateAddress('street', e.target.value)}
        />
      </div>

      <div className="state-display">
        <h4>当前状态:</h4>
        <pre>{JSON.stringify(user, null, 2)}</pre>
      </div>
    </div>
  )
}

// 数组状态管理
function ArrayState() {
  const [items, setItems] = useState(['苹果', '香蕉', '橙子'])
  const [newItem, setNewItem] = useState('')

  const addItem = () => {
    if (newItem.trim()) {
      setItems([...items, newItem.trim()])
      setNewItem('')
    }
  }

  const removeItem = (index) => {
    setItems(items.filter((_, i) => i !== index))
  }

  const updateItem = (index, value) => {
    const newItems = [...items]
    newItems[index] = value
    setItems(newItems)
  }

  return (
    <div className="array-state">
      <h3>数组状态管理</h3>
      
      <div className="add-item">
        <input 
          type="text"
          value={newItem}
          onChange={(e) => setNewItem(e.target.value)}
          placeholder="添加新项目"
          onKeyPress={(e) => e.key === 'Enter' && addItem()}
        />
        <button onClick={addItem}>添加</button>
      </div>

      <ul className="item-list">
        {items.map((item, index) => (
          <li key={index}>
            <input 
              type="text"
              value={item}
              onChange={(e) => updateItem(index, e.target.value)}
            />
            <button onClick={() => removeItem(index)}>删除</button>
          </li>
        ))}
      </ul>

      <p>项目数量: {items.length}</p>
    </div>
  )
}

// 函数式更新
function FunctionalUpdate() {
  const [count, setCount] = useState(0)

  // 使用函数式更新，确保基于最新的状态值进行更新
  const increment = () => {
    setCount(prevCount => prevCount + 1)
  }

  const incrementMultiple = () => {
    // 连续多次调用函数式更新
    setCount(prev => prev + 1)
    setCount(prev => prev + 1)
    setCount(prev => prev + 1)
  }

  return (
    <div className="functional-update">
      <h3>函数式更新</h3>
      <p>当前计数: {count}</p>
      
      <button onClick={increment}>增加 1</button>
      <button onClick={incrementMultiple}>增加 3</button>
      <button onClick={() => setCount(0)}>重置</button>
      
      <div className="explanation">
        <p>函数式更新确保基于最新的状态值进行更新，避免状态更新的竞态条件。</p>
      </div>
    </div>
  )
}

function StateManagement() {
  return (
    <div className="example-page">
      <div className="example-header">
        <h1>状态管理 (useState)</h1>
        <p>学习 React 中的状态管理，掌握 useState Hook 的各种用法</p>
      </div>

      <div className="example-section">
        <h2>1. 基本计数器</h2>
        <p>最简单的状态管理示例：</p>
        
        <div className="code-block">
{`const [count, setCount] = useState(0)

return (
  <div>
    <h3>计数器: {count}</h3>
    <button onClick={() => setCount(count + 1)}>增加</button>
    <button onClick={() => setCount(count - 1)}>减少</button>
  </div>
)`}
        </div>

        <div className="demo-container">
          <div className="demo-title">计数器示例：</div>
          <div className="demo-content">
            <Counter />
          </div>
        </div>
      </div>

      <div className="example-section">
        <h2>2. 文本输入</h2>
        <p>处理文本输入的状态：</p>
        
        <div className="demo-container">
          <div className="demo-title">文本输入示例：</div>
          <div className="demo-content">
            <TextInput />
          </div>
        </div>
      </div>

      <div className="example-section">
        <h2>3. 复选框状态</h2>
        <p>处理复选框的选中状态：</p>
        
        <div className="demo-container">
          <div className="demo-title">复选框示例：</div>
          <div className="demo-content">
            <CheckboxExample />
          </div>
        </div>
      </div>

      <div className="example-section">
        <h2>4. 单选按钮状态</h2>
        <p>处理单选按钮的选择状态：</p>
        
        <div className="demo-container">
          <div className="demo-title">单选按钮示例：</div>
          <div className="demo-content">
            <RadioExample />
          </div>
        </div>
      </div>

      <div className="example-section">
        <h2>5. 下拉选择状态</h2>
        <p>处理下拉选择框的状态：</p>
        
        <div className="demo-container">
          <div className="demo-title">下拉选择示例：</div>
          <div className="demo-content">
            <SelectExample />
          </div>
        </div>
      </div>

      <div className="example-section">
        <h2>6. 对象状态管理</h2>
        <p>管理复杂对象状态，使用展开运算符保持不可变性：</p>
        
        <div className="code-block">
{`const [user, setUser] = useState({
  name: '',
  email: '',
  address: {
    city: '',
    street: ''
  }
})

// 更新嵌套对象
const updateAddress = (field, value) => {
  setUser(prev => ({
    ...prev,
    address: {
      ...prev.address,
      [field]: value
    }
  }))
}`}
        </div>

        <div className="demo-container">
          <div className="demo-title">对象状态示例：</div>
          <div className="demo-content">
            <ObjectState />
          </div>
        </div>
      </div>

      <div className="example-section">
        <h2>7. 数组状态管理</h2>
        <p>管理数组状态的添加、删除和修改：</p>
        
        <div className="code-block">
{`// 添加项目
const addItem = (newItem) => {
  setItems([...items, newItem])
}

// 删除项目
const removeItem = (index) => {
  setItems(items.filter((_, i) => i !== index))
}

// 更新项目
const updateItem = (index, value) => {
  const newItems = [...items]
  newItems[index] = value
  setItems(newItems)
}`}
        </div>

        <div className="demo-container">
          <div className="demo-title">数组状态示例：</div>
          <div className="demo-content">
            <ArrayState />
          </div>
        </div>
      </div>

      <div className="example-section">
        <h2>8. 函数式更新</h2>
        <p>使用函数式更新确保基于最新状态进行更新：</p>
        
        <div className="code-block">
{`// 函数式更新
const increment = () => {
  setCount(prevCount => prevCount + 1)
}

// 连续多次更新
const incrementMultiple = () => {
  setCount(prev => prev + 1)
  setCount(prev => prev + 1)
  setCount(prev => prev + 1)
}`}
        </div>

        <div className="demo-container">
          <div className="demo-title">函数式更新示例：</div>
          <div className="demo-content">
            <FunctionalUpdate />
          </div>
        </div>
      </div>

      <div className="tip">
        <strong>useState 最佳实践：</strong>
        <ul>
          <li>保持状态简单，避免过度嵌套</li>
          <li>使用函数式更新避免状态更新的竞态条件</li>
          <li>更新对象和数组时保持不可变性</li>
          <li>相关的状态可以考虑合并为一个对象</li>
          <li>对于复杂状态管理，考虑使用 useReducer</li>
        </ul>
      </div>
    </div>
  )
}

export default StateManagement